// 简化的性能工具函数

// 防抖函数
export function debounce<T extends (...args: any[]) => any>(func: T, delay: number): (...args: Parameters<T>) => void {
    let timeoutId: number
    return (...args: Parameters<T>) => {
        clearTimeout(timeoutId)
        timeoutId = setTimeout(() => func(...args), delay)
    }
}

// 节流函数
export function throttle<T extends (...args: any[]) => any>(func: T, delay: number): (...args: Parameters<T>) => void {
    let lastCall = 0
    return (...args: Parameters<T>) => {
        const now = Date.now()
        if (now - lastCall >= delay) {
            lastCall = now
            func(...args)
        }
    }
}

// 延迟执行
export const delay = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms))

// 空闲时执行
export const runOnIdle = (callback: () => void): void => {
    // #ifdef H5
    if ('requestIdleCallback' in window) {
        requestIdleCallback(callback)
    } else {
        setTimeout(callback, 0)
    }
    // #endif
    // #ifdef MP-WEIXIN || APP-PLUS
    setTimeout(callback, 0)
    // #endif
}

// 批量执行任务
export async function batchExecute<T>(tasks: (() => Promise<T>)[], batchSize = 3): Promise<T[]> {
    const results: T[] = []
    for (let i = 0; i < tasks.length; i += batchSize) {
        const batch = tasks.slice(i, i + batchSize)
        const batchResults = await Promise.all(batch.map((task) => task()))
        results.push(...batchResults)
    }
    return results
}

// 简单的并发控制
export const createConcurrencyController = (limit = 3) => {
    let running = 0
    const queue: Array<() => void> = []

    const execute = async <T>(task: () => Promise<T>): Promise<T> => {
        return new Promise((resolve, reject) => {
            const run = async () => {
                running++
                try {
                    const result = await task()
                    resolve(result)
                } catch (error) {
                    reject(error)
                } finally {
                    running--
                    if (queue.length > 0 && running < limit) {
                        const next = queue.shift()
                        if (next) next()
                    }
                }
            }

            if (running < limit) {
                run()
            } else {
                queue.push(run)
            }
        })
    }

    return { execute }
}

// 简单的内存缓存
const cache = new Map<string, { data: any; expiry: number }>()

export const memoryManager = {
    set(key: string, data: any, ttl = 3600000): void {
        cache.set(key, {
            data,
            expiry: Date.now() + ttl
        })
    },

    get(key: string): any {
        const item = cache.get(key)
        if (!item) return null

        if (Date.now() > item.expiry) {
            cache.delete(key)
            return null
        }

        return item.data
    },

    clear(): void {
        cache.clear()
    }
}

// 简单的性能监控
const performanceMarks = new Map<string, number>()

export const performanceMonitor = {
    mark(name: string): void {
        performanceMarks.set(name, Date.now())
    },

    measure(startMark: string, endMark?: string): number {
        const startTime = performanceMarks.get(startMark)
        const endTime = endMark ? performanceMarks.get(endMark) : Date.now()

        if (!startTime || !endTime) return 0
        return endTime - startTime
    },

    clear(): void {
        performanceMarks.clear()
    }
}

// 简单的图片预加载
const preloadedImages = new Set<string>()

export const preloadImage = async (url: string): Promise<boolean> => {
    if (preloadedImages.has(url)) return true

    try {
        await new Promise((resolve, reject) => {
            // #ifdef H5
            const img = new Image()
            img.onload = resolve
            img.onerror = reject
            img.src = url
            // #endif
            // #ifdef MP-WEIXIN || APP-PLUS
            uni.getImageInfo({
                src: url,
                success: resolve,
                fail: reject
            })
            // #endif
        })

        preloadedImages.add(url)
        return true
    } catch (error) {
        console.error('Failed to preload image:', url)
        return false
    }
}

export const preloadImages = async (urls: string[]): Promise<boolean[]> => {
    return Promise.all(urls.map((url) => preloadImage(url)))
}

// 简化的性能优化初始化
export function initPerformanceOptimization(): void {
    if (import.meta.env.MODE === 'development') {
        console.log('Performance optimization initialized')
    }

    // 监听内存警告
    // #ifdef MP-WEIXIN
    try {
        uni.onMemoryWarning(() => {
            console.warn('Memory warning detected')
        })
    } catch (e) {
        // 忽略错误
    }
    // #endif
}
